package com.lonely.order.support.synchronizer.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lonely.common.annotation.RedisLock;
import com.lonely.common.core.domain.BaseEntity;
import com.lonely.common.utils.FzzfDateUtil;
import com.lonely.common.utils.JsonUtil;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.deliver.domain.dto.SyncProgressDTO;
import com.lonely.deliver.domain.entity.SysOrderDeliver;
import com.lonely.deliver.enums.OrderDeliverEnum;
import com.lonely.deliver.service.IOrderDeliverService;
import com.lonely.framework.websocket.WebSocketUtil;
import com.lonely.order.domain.dto.api.QueryDeliverOrderReqDTO;
import com.lonely.order.domain.dto.api.QueryDeliverOrderResDTO;
import com.lonely.order.domain.entity.SysOrder;
import com.lonely.order.domain.entity.SysSheinOpenApiSecret;
import com.lonely.order.enums.OrderEnum;
import com.lonely.order.service.IMesApiService;
import com.lonely.order.service.IOrderService;
import com.lonely.order.service.ISysSheinOpenApiSecretService;
import com.lonely.order.support.synchronizer.SynchronizedOrderDeliverThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/7/31 15:30
 * @description: 同步订单发货单数据服务
 */
@Service
@Slf4j
public class SynchronizerOrderDeliverService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IMesApiService mesApiService;

    @Autowired
    private ISysSheinOpenApiSecretService sheinOpenApiSecretService;

    @Autowired
    private IOrderDeliverService orderDeliverService;

    // 待排除的订单状态
//    private static final List<Integer> NEED_EXCLUDE_ORDER_STATUS = Lists.newArrayList(
//            OrderEnum.OrderStatus.COMPLETED.getStatus(),
//            OrderEnum.OrderStatus.REPEALED.getStatus()
//    );

    /**
     * 同步订单发货单
     */
    @RedisLock(key = "'order:synchronizedOrderDeliver'", waitTime = 2000)
    @Transactional(rollbackFor = Exception.class)
    public void synchronizerOrderDeliver() {

//        // 获取所有shein的订单号,且状态为已完成的数据
//        List<SysOrder> sysOrders = this.orderService.list(new LambdaQueryWrapper<SysOrder>()
//                        .eq(SysOrder::getOrderSource, OrderEnum.OrderSourceEnum.SHEIN.getOrderSource())
////                .eq(SysOrder::getFactoryId, 1L) // 测试，只获取工厂1 的订单数据
////                        .eq(SysOrder::getOriginalOrderStatus, "已完成")
//        );

        // TODO 逻辑调整，改成查询订单发货单中状态为非已入仓的订单来进行同步
        List<Long> orderIds = this.orderDeliverService.list(new LambdaQueryWrapper<SysOrderDeliver>()
                .ne(SysOrderDeliver::getStatus, OrderDeliverEnum.StatusEnum.ALREADY_WAREHOUSED.getStatus())
        ).stream().map(SysOrderDeliver::getOrderId).distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(orderIds)) {
            log.debug("没有待同步发货单的订单,同步结束...");
            this.sendCompletedMessage("没有待同步发货单的订单");
            return;
        }
        List<SysOrder> sysOrders = this.orderService.list(new LambdaQueryWrapper<SysOrder>()
                .eq(SysOrder::getOrderSource, OrderEnum.OrderSourceEnum.SHEIN.getOrderSource())
                .in(SysOrder::getId, orderIds)
        );
        if (CollUtil.isEmpty(sysOrders)) {
            log.debug("没有待同步发货单的订单,同步结束...");
//            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildCompletedResult("没有待同步发货单的订单"));
            this.sendCompletedMessage("没有待同步发货单的订单");
            return;
        }

        // 获取工厂密钥信息
        List<Long> factoryIds = sysOrders.stream().map(SysOrder::getFactoryId).distinct().collect(Collectors.toList());
        Map<Long, SysSheinOpenApiSecret> factorySecretMap = sheinOpenApiSecretService.getSheinOpenApiSecretMap(factoryIds);

        if (CollUtil.isEmpty(factorySecretMap)) {
            log.debug("没有查询到工厂密钥信息,同步结束...");
            this.sendCompletedMessage("没有查询到工厂密钥信息");
//            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildCompletedResult("没有查询到工厂密钥信息"));
            return;
        }

        // 订单号与订单id的映射
        Map<Long, Long> productOrderMap = sysOrders.stream().collect(Collectors.toMap(SysOrder::getProduceOrderId, BaseEntity::getId, (x, y) -> x));

        //遍历所有工厂的订单
        Map<Long, List<QueryDeliverOrderResDTO>> factoryOrderDeliverMap = new LinkedHashMap<>();
        long needSynchronizedOrderDeliverCount = 0;
        log.debug("开始获取接口中的发货单数据...");
//        WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(0, "开始获取接口中的发货单数据"));
        this.sendHasNotProgressMessage("开始获取接口中的发货单数据");
        for (Map.Entry<Long, SysSheinOpenApiSecret> openApiSecretEntry : factorySecretMap.entrySet()) {
            // 筛选出当前工厂的订单信息
            List<SysOrder> currentFactoryOrders = sysOrders.stream().filter(x -> Objects.equals(x.getFactoryId(), openApiSecretEntry.getKey())).collect(Collectors.toList());
            if (CollUtil.isEmpty(currentFactoryOrders)) {
                continue;
            }

            // 订单分批
//            log.debug("开始同步工厂：{}的订单发货单数据...", openApiSecretEntry.getKey());
            List<List<SysOrder>> currentOrderGroups = CollUtil.split(currentFactoryOrders, 100);
            for (List<SysOrder> currentOrderGroup : currentOrderGroups) {
                QueryDeliverOrderReqDTO reqDTO = new QueryDeliverOrderReqDTO();
                reqDTO.setProduceOrderIdList(currentOrderGroup.stream().map(SysOrder::getProduceOrderId).collect(Collectors.toList()));
                List<QueryDeliverOrderResDTO> deliverOrderResDTOS = this.mesApiService.queryDeliverOrder(openApiSecretEntry.getValue(), reqDTO);
                if (CollUtil.isEmpty(deliverOrderResDTOS)) {
                    continue;
                }

                // 过滤掉自订单号为空的数据
                deliverOrderResDTOS = deliverOrderResDTOS.stream().filter(x -> StrUtil.isNotBlank(x.getSubProduceOrderCode())).collect(Collectors.toList());
                if (CollUtil.isEmpty(deliverOrderResDTOS)) {
                    continue;
                }

                needSynchronizedOrderDeliverCount += deliverOrderResDTOS.stream().map(QueryDeliverOrderResDTO::getProduceOrderId).distinct().count();
                factoryOrderDeliverMap.computeIfAbsent(openApiSecretEntry.getKey(), k -> new ArrayList<>()).addAll(deliverOrderResDTOS);


                // 等待2秒钟，避免触发限流
                ThreadUtil.sleep(2000);

            }
//            log.debug("同步工厂：{}的订单发货单数据已完成...", openApiSecretEntry.getKey());
        }
        log.debug("已获取接口中的发货单数据...");
//        WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(0, "已获取接口中的发货单数据"));
        this.sendHasNotProgressMessage("已获取接口中的发货单数据");

        if (needSynchronizedOrderDeliverCount == 0) {
            // 没有待同步的发货单数据
            log.debug("没有待同步的发货单数据,同步结束...");
//            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildCompletedResult("没有待同步的发货单数据"));
            this.sendCompletedMessage("没有待同步的发货单数据");
            return;
        }

        SynchronizedOrderDeliverThreadLocal.setTotalSize((int) needSynchronizedOrderDeliverCount);

        // 开始同步订单发货单数据
        for (Map.Entry<Long, List<QueryDeliverOrderResDTO>> currentFactoryOrders : factoryOrderDeliverMap.entrySet()) {
            log.debug("开始同步工厂：{}的订单发货单数据...", currentFactoryOrders.getKey());
            this.currentOrderGroupHandler(currentFactoryOrders.getValue(), productOrderMap);
            log.debug("同步工厂：{}的订单发货单数据已完成...", currentFactoryOrders.getKey());
        }

        // 同步完成
//        WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildCompletedResult("同步完成"));
        this.sendCompletedMessage("同步完成");
    }

    /**
     * 发送同步完成消息
     */
    private void sendCompletedMessage(String message) {
        if (SynchronizedOrderDeliverThreadLocal.getIsWebsocket()) {
            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildCompletedResult(message));
        }
    }

    /**
     * 发送同步进行中(有进度的)消息
     */
    private void sendHasProgressMessage(String message) {
        if (SynchronizedOrderDeliverThreadLocal.getIsWebsocket()) {
            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(SynchronizedOrderDeliverThreadLocal.getProgress(), message));
        }
    }


    /**
     * 发送同步进行中(没有进度的)消息
     */
    private void sendHasNotProgressMessage(String message) {
        if (SynchronizedOrderDeliverThreadLocal.getIsWebsocket()) {
            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(0, message));
        }
    }


    /**
     * 当前订单组处理
     *
     * @param deliverOrderResDTOS
     * @param productOrderMap
     */
    private void currentOrderGroupHandler(List<QueryDeliverOrderResDTO> deliverOrderResDTOS, Map<Long, Long> productOrderMap) {

        // 同步到数据库中
        List<String> deliverProduceOrderIds = deliverOrderResDTOS.stream().map(QueryDeliverOrderResDTO::getProduceOrderId).distinct().collect(Collectors.toList());

        List<SysOrderDeliver> existsOrderDelivers = this.orderDeliverService.list(new LambdaQueryWrapper<SysOrderDeliver>()
                .in(SysOrderDeliver::getProduceOrderId, deliverProduceOrderIds)
        );
        List<String> existsProduceOrderIds = existsOrderDelivers.stream().map(SysOrderDeliver::getProduceOrderId).distinct().collect(Collectors.toList());

        // 找出待添加的订单号数据
        List<String> needAddProduceOrderIds = CollUtil.subtractToList(deliverProduceOrderIds, existsProduceOrderIds);
        if (CollUtil.isNotEmpty(needAddProduceOrderIds)) {
            List<SysOrderDeliver> needAddDelivers = deliverOrderResDTOS.stream().filter(x -> needAddProduceOrderIds.contains(x.getProduceOrderId())).map(x -> buildAddOrderDeliver(x, productOrderMap)).collect(Collectors.toList());
            this.orderDeliverService.saveBatch(needAddDelivers);

            // 更新同步进度
            SynchronizedOrderDeliverThreadLocal.addExecutedSize(needAddDelivers.size());

            // 发送进度
            this.sendHasProgressMessage(StrUtil.EMPTY);
//            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(SynchronizedOrderDeliverThreadLocal.getProgress(), StrUtil.EMPTY));
        }

        // 找出待删除的订单号数据
        List<String> needRemoveProduceOrderIds = CollUtil.subtractToList(existsProduceOrderIds, deliverProduceOrderIds);
        if (CollUtil.isNotEmpty(needRemoveProduceOrderIds)) {
            this.orderDeliverService.remove(new LambdaQueryWrapper<SysOrderDeliver>()
                    .in(SysOrderDeliver::getProduceOrderId, needRemoveProduceOrderIds)
            );

            // 更新同步进度
            SynchronizedOrderDeliverThreadLocal.addExecutedSize(needRemoveProduceOrderIds.size());

            // 发送进度
            this.sendHasProgressMessage(StrUtil.EMPTY);
//            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(SynchronizedOrderDeliverThreadLocal.getProgress(), StrUtil.EMPTY));
        }

        // 待修改的订单号数据
        for (String existsProduceOrderId : existsProduceOrderIds) {
            this.doUpdateCurrentOrderLocalData(existsOrderDelivers, existsProduceOrderId, deliverOrderResDTOS, productOrderMap);

            // 更新同步进度
            SynchronizedOrderDeliverThreadLocal.addExecutedSize(1);
            this.sendHasProgressMessage(StrUtil.EMPTY);
//            WebSocketUtil.sendToUser(SecurityUtils.getUsername(), SynchronizedOrderDeliverThreadLocal.getDestination(), SyncProgressDTO.buildProgressResult(SynchronizedOrderDeliverThreadLocal.getProgress(), StrUtil.EMPTY));
        }
    }

    /**
     * 更新当前本地的订单发货单数据
     *
     * @param existsOrderDelivers
     * @param existsProduceOrderId
     * @param deliverOrderResDTOS
     * @param productOrderMap
     */
    private void doUpdateCurrentOrderLocalData(List<SysOrderDeliver> existsOrderDelivers, String existsProduceOrderId,
                                               List<QueryDeliverOrderResDTO> deliverOrderResDTOS, Map<Long, Long> productOrderMap) {

        // 处理子订单号为空的数据,将该订单中子订单号为空的数据直接删除,使用当前接口的中数据重新入库
        this.doHandlerSubProduceOrderCodeIsEmptyDeliver(existsOrderDelivers, existsProduceOrderId, deliverOrderResDTOS, productOrderMap);

        // 处理子订单号为不为空的数据
        this.doHandlerSubProduceOrderCodeNotEmptyDeliver(existsOrderDelivers, existsProduceOrderId, deliverOrderResDTOS, productOrderMap);
    }

    /**
     * 处理子订单号不为空的发货单数据
     *
     * @param existsOrderDelivers
     * @param existsProduceOrderId
     * @param deliverOrderResDTOS
     * @param productOrderMap
     */
    private void doHandlerSubProduceOrderCodeNotEmptyDeliver(List<SysOrderDeliver> existsOrderDelivers, String existsProduceOrderId,
                                                             List<QueryDeliverOrderResDTO> deliverOrderResDTOS, Map<Long, Long> productOrderMap) {

        // 当前订单号已存在的发货单数据
        List<SysOrderDeliver> existsCurrentProduceOrderDelivers = existsOrderDelivers.stream().filter(x -> Objects.equals(x.getProduceOrderId(), existsProduceOrderId))
                .filter(x -> StrUtil.isNotBlank(x.getSubProduceOrderCode()))
                .collect(Collectors.toList());
        List<String> existsSubProduceOrderCodes = existsCurrentProduceOrderDelivers.stream().map(SysOrderDeliver::getSubProduceOrderCode).collect(Collectors.toList());


        // 当前订单号最新的发货单数据
        List<QueryDeliverOrderResDTO> newCurrentProduceOrderDelivers = deliverOrderResDTOS.stream().filter(x -> Objects.equals(x.getProduceOrderId(), existsProduceOrderId))
                .filter(x -> StrUtil.isNotBlank(x.getSubProduceOrderCode()))
                .collect(Collectors.toList());
        List<String> newSubProduceOrderCodes = newCurrentProduceOrderDelivers.stream().map(QueryDeliverOrderResDTO::getSubProduceOrderCode).collect(Collectors.toList());
        Map<String, QueryDeliverOrderResDTO> newSubProduceOrderCodeMap = newCurrentProduceOrderDelivers.stream().collect(Collectors.toMap(QueryDeliverOrderResDTO::getSubProduceOrderCode, Function.identity(), (x, y) -> x));

        // 找出待新增的发货单数据
        List<String> needAddSubProduceOrderCodes = CollUtil.subtractToList(newSubProduceOrderCodes, existsSubProduceOrderCodes);

        // 找出待删除的发货单数据
        List<String> needRemoveSubProduceOrderCodes = CollUtil.subtractToList(existsSubProduceOrderCodes, newSubProduceOrderCodes);

        // 找出待修改的发货单数据
        List<SysOrderDeliver> needUpdateOrderDelivers = existsOrderDelivers.stream().filter(x -> newSubProduceOrderCodes.contains(x.getSubProduceOrderCode())).peek(x -> {
            QueryDeliverOrderResDTO queryDeliverOrderResDTO = newSubProduceOrderCodeMap.get(x.getSubProduceOrderCode());
            BeanUtils.copyProperties(queryDeliverOrderResDTO, x);
            x.setOrderId(productOrderMap.get(Convert.toLong(queryDeliverOrderResDTO.getProduceOrderId())));
            x.setDeliveryInfo(JsonUtil.toJsonString(queryDeliverOrderResDTO.getDeliveryInfo()));
            x.setInspectionTime(FzzfDateUtil.parseDateTime(queryDeliverOrderResDTO.getInspectionTime()));
            x.setReturnInfo(JsonUtil.toJsonString(queryDeliverOrderResDTO.getReturnInfo()));
            x.setReturnTime(FzzfDateUtil.parseDateTime(queryDeliverOrderResDTO.getReturnTime()));
            x.setSendTime(FzzfDateUtil.parseDateTime(queryDeliverOrderResDTO.getSendTime()));
            x.setStoreInfo(JsonUtil.toJsonString(queryDeliverOrderResDTO.getStoreInfo()));
            x.setStoreTime(FzzfDateUtil.parseDateTime(queryDeliverOrderResDTO.getStoreTime()));
            x.setStatus(queryDeliverOrderResDTO.getDeliverStatus());
            x.setUpdateBy(SynchronizedOrderDeliverThreadLocal.getCreateBy());
            x.setReason(OrderDeliverEnum.ReasonEnum.getReason(queryDeliverOrderResDTO.getReasonStr()));
            x.setDeliverStatus(this.convertStatus(queryDeliverOrderResDTO.getDeliverStatusStr()).getStatus());
        }).collect(Collectors.toList());

        // 新增数据入库
        if (CollUtil.isNotEmpty(needAddSubProduceOrderCodes)) {
            List<SysOrderDeliver> needAddOrderDelivers = newCurrentProduceOrderDelivers.stream().filter(x -> newSubProduceOrderCodes.contains(x.getSubProduceOrderCode()))
                    .map(x -> buildAddOrderDeliver(x, productOrderMap)).collect(Collectors.toList());
            this.orderDeliverService.saveBatch(needAddOrderDelivers);
        }

        // 删除 数据
        if (CollUtil.isNotEmpty(needRemoveSubProduceOrderCodes)) {
            this.orderDeliverService.remove(new LambdaQueryWrapper<SysOrderDeliver>()
                    .eq(SysOrderDeliver::getProduceOrderId, existsProduceOrderId)
                    .in(SysOrderDeliver::getSubProduceOrderCode, needRemoveSubProduceOrderCodes)
            );
        }

        // 修改数据入库
        if (CollUtil.isNotEmpty(needUpdateOrderDelivers)) {
            this.orderDeliverService.updateBatchById(needUpdateOrderDelivers);
        }

    }


    /**
     * 处理子订单号为空的发货单数据
     *
     * @param existsOrderDelivers
     * @param existsProduceOrderId
     * @param deliverOrderResDTOS
     * @param productOrderMap
     */
    private void doHandlerSubProduceOrderCodeIsEmptyDeliver(List<SysOrderDeliver> existsOrderDelivers, String existsProduceOrderId,
                                                            List<QueryDeliverOrderResDTO> deliverOrderResDTOS, Map<Long, Long> productOrderMap) {


        // 将该订单中子订单号为空的数据直接删除,使用当前接口的中数据重新入库
        List<Long> existsCurrentProduceOrderSubProduceOrderCodeIsEmptyDeliverIds = existsOrderDelivers.stream().filter(x -> Objects.equals(x.getProduceOrderId(), existsProduceOrderId))
                .filter(x -> StrUtil.isBlank(x.getSubProduceOrderCode()))
                .map(BaseEntity::getId)
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(existsCurrentProduceOrderSubProduceOrderCodeIsEmptyDeliverIds)) {
            this.orderDeliverService.removeByIds(existsCurrentProduceOrderSubProduceOrderCodeIsEmptyDeliverIds);
        }

        // 接口返回中的子订单号为空的数据
        List<QueryDeliverOrderResDTO> newAddCurrentProduceOrderDelivers = deliverOrderResDTOS.stream().filter(x -> Objects.equals(x.getProduceOrderId(), existsProduceOrderId))
                .filter(x -> StrUtil.isBlank(x.getSubProduceOrderCode()))
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(newAddCurrentProduceOrderDelivers)) {
            List<SysOrderDeliver> orderDelivers = newAddCurrentProduceOrderDelivers.stream().map(x -> buildAddOrderDeliver(x, productOrderMap)).collect(Collectors.toList());
            this.orderDeliverService.saveBatch(orderDelivers);
        }

    }


    /**
     * 基于接口相应的订单发货单数据构建本地数据
     *
     * @param deliverOrderResDTO
     * @param productOrderMap
     * @return
     */
    public SysOrderDeliver buildAddOrderDeliver(QueryDeliverOrderResDTO deliverOrderResDTO, Map<Long, Long> productOrderMap) {
        SysOrderDeliver sysOrderDeliver = new SysOrderDeliver();
        BeanUtils.copyProperties(deliverOrderResDTO, sysOrderDeliver);
        sysOrderDeliver.setOrderId(productOrderMap.get(Convert.toLong(deliverOrderResDTO.getProduceOrderId())));
        sysOrderDeliver.setDeliveryInfo(JsonUtil.toJsonString(deliverOrderResDTO.getDeliveryInfo()));
        sysOrderDeliver.setInspectionTime(FzzfDateUtil.parseDateTime(deliverOrderResDTO.getInspectionTime()));
        sysOrderDeliver.setReturnInfo(JsonUtil.toJsonString(deliverOrderResDTO.getReturnInfo()));
        sysOrderDeliver.setReturnTime(FzzfDateUtil.parseDateTime(deliverOrderResDTO.getReturnTime()));
        sysOrderDeliver.setSendTime(FzzfDateUtil.parseDateTime(deliverOrderResDTO.getSendTime()));
        sysOrderDeliver.setStoreInfo(JsonUtil.toJsonString(deliverOrderResDTO.getStoreInfo()));
        sysOrderDeliver.setStoreTime(FzzfDateUtil.parseDateTime(deliverOrderResDTO.getStoreTime()));
        sysOrderDeliver.setStatus(convertStatus(deliverOrderResDTO.getDeliverStatusStr()).getStatus());
        sysOrderDeliver.setCreateBy(SynchronizedOrderDeliverThreadLocal.getCreateBy());
        sysOrderDeliver.setUpdateBy(SynchronizedOrderDeliverThreadLocal.getCreateBy());

        sysOrderDeliver.setReason(OrderDeliverEnum.ReasonEnum.getReason(deliverOrderResDTO.getReasonStr()));
        sysOrderDeliver.setDeliverStatus(this.convertStatus(deliverOrderResDTO.getDeliverStatusStr()).getStatus());
        return sysOrderDeliver;
    }

    /**
     * 提取发货单状态
     *
     * @param deliverStatusStr
     * @return
     */
    private OrderDeliverEnum.StatusEnum convertStatus(String deliverStatusStr) {

        // TODO 暂时这样设置，实际待确认
        if (StrUtil.isBlank(deliverStatusStr)) {
            return OrderDeliverEnum.StatusEnum.TO_BE_PACKED;
        }

        switch (deliverStatusStr) {
            case "待打包":
                return OrderDeliverEnum.StatusEnum.TO_BE_PACKED;
            case "已打包":
            case "待发货":
                return OrderDeliverEnum.StatusEnum.PACKED;
            case "催发货":
                return OrderDeliverEnum.StatusEnum.URGE_DELIVERY;
            case "待收货":
                return OrderDeliverEnum.StatusEnum.PENDING_RECEIPT;
            case "已退货":
                return OrderDeliverEnum.StatusEnum.RECEIVED;
            case "待退货":
                return OrderDeliverEnum.StatusEnum.PENDING_RETURN;
            case "已入仓":
                return OrderDeliverEnum.StatusEnum.ALREADY_WAREHOUSED;
        }

        // 其他默认都为待打包
        return OrderDeliverEnum.StatusEnum.TO_BE_PACKED;
    }

}
